class StarElement extends Element {
  constructor(layoutNode, context) {
    super(layoutNode, context)
  }

  draw() {
    let { react, style, attrs } = this.layoutNode
    let initConfig = {
      num: 5,
      R: react.width,
      r: react.width / 2,
      x: react.left,
      y: react.top,
      rotate: 45,
      fillStyle: '#FCFA31',
      lineJoin: 'round',
      bw: 2,
      lineCap: '',
      fill: 'false',
      stroke: 'true',
    }
    this.star(Object.assign(initConfig, attrs))
  }
  /**
   * 绘制n角星
   * @param num 星星数量
   * @param R 中心到顶点距离
   * @param r 中心到凹点距离
   * @param x 左上角X坐标Y
   * @param y 左上角坐标
   * @param rotate 旋转角度
   * @param bw 线宽
   * @param strokeStyle 线颜色
   * @param fillStyle 填充颜色
   * @param lineJoin 接头样式
   * @param lineCap
   */
  star(config) {
    this.ctx.beginPath()
    let border = +config.bw
    let num = +config.num
    let rot = +config.rotate
    let R = +config.R
    let r = +config.r
    let x = +config.x
    let y = +config.y

    for (let i = 0; i < num; i++) {
      let perDeg = 360 / num
      let degA = perDeg / 2 / 2
      let degB = 360 / (num - 1) / 2 - degA / 2 + degA
      this.ctx.lineTo(
        Math.cos(((degA + perDeg * i - rot) / 180) * Math.PI) * R +
          x +
          border +
          R * Math.cos((degA / 180) * Math.PI),
        -Math.sin(((degA + perDeg * i - rot) / 180) * Math.PI) * R + y + border + R
      )
      this.ctx.lineTo(
        Math.cos(((degB + perDeg * i - rot) / 180) * Math.PI) * r +
          x +
          border +
          R * Math.cos((degA / 180) * Math.PI),
        -Math.sin(((degB + perDeg * i - rot) / 180) * Math.PI) * r + y + border + R
      )
    }
    this.ctx.closePath() //会封闭图形

    this.ctx.lineWidth = border
    this.ctx.strokeStyle = config.strokeStyle
    this.ctx.fillStyle = config.fillStyle
    this.ctx.lineJoin = config.lineJoin
    this.ctx.lineCap = config.lineCap

    if (config.fill === 'true') {
      this.ctx.fill()
    }
    if (config.stroke === 'true') {
      this.ctx.stroke() //绘制
    }
  }
}
